#!coding:utf-8
import locale # for proper curses unicode support
locale.setlocale(locale.LC_ALL,"")

import curses

screen = curses.initscr()
curses.noecho() # pressed keys don't displayed on screen
curses.curs_set(0) # cursor not visible
curses.start_color()
curses.init_pair(1,curses.COLOR_WHITE,curses.COLOR_BLACK)
curses.init_pair(2,curses.COLOR_RED,curses.COLOR_BLACK)


screen.border(0)
screen.addstr(1,1,"Привіт світе! ")
screen.addstr(2,1,"Натисніть q щоб вийти. ",curses.color_pair(2))
screen.refresh()

def safeprint(self,y,x,msg):
	if x< 0 or y < 0 : return
	maxy,maxx = self.getmaxyx()	
	if y>=maxy: return
	if x>=maxx: return
	l = len(msg)
	d= maxx - (x+l)-1
	self.addstr(1,0,"l=%d, x=%d, d=%d" %(l,x,d))
	if d<0:
		self.addstr(y,x,msg[:d])
	else:
		self.addstr(y,x,msg)

maxy,maxx=screen.getmaxyx()


variant_keys = "jfkdlshg;a"
def menu(variants):
	for i,v in enumerate(variants):
		safeprint(screen,2+i,10,variant_keys[i]+":"+v)
	screen.refresh()
	x = screen.getch()	
	return variant_keys.index(chr(x))

x = 3
y = 3
while 1:
	key = screen.getch()
	if key==ord('q'): break
	if key==ord('j'): y+=1
	if key==ord('k'): y-=1
	if key==ord('h'): x-=1
	if key==ord('l'): x+=1
	if x>= maxx: x = maxx-1
	if y>= maxy: y = maxy-1
	if x< 0: x =0
	if y< 0: y =0
	screen.erase()
	screen.addstr(0,0,"%d, %d" %(maxx,maxy))
	safeprint(screen,y,x,"#%d,%d" % (x,y))
	#x = menu(["Milk","Tea","Coffe","Water"])
	safeprint(screen,40,20,str(x))
	screen.refresh()

curses.echo()
curses.endwin()
